package club.lulibo.lbchart;

import android.content.Context;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import java.util.ArrayList;
import java.util.List;

public class Chart extends WebView {

    /**
     * 默认false
     * 在EChart.html和EChart.js中因开发调试多处调用了function toast(msg) 可以设置为true开启调试模式
     */
    private boolean isDebug = false;


    /**
     * 存放在第一时间需要Android调用js的function
     * 因为在第一次见EChart.html及EChart.js还没有加载完成，而Java代码却是在第一时间调用了
     * 所以需要等到html的标签及js加载成功后再调用，在WebViewClient中的onPageFinished方法中
     */
    private List<String> shouldCallJsFunctionArray = new ArrayList<String>();

    public void setDebug(boolean isDebug) {
        this.isDebug = isDebug;
    }

    public boolean isDebug() {

        return isDebug;
    }

    public Chart(Context context) {
        this(context, null);
    }

    public Chart(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public Chart(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        initWebViewClient();

        init();
    }

    private void init() {
        //
        WebSettings webSettings = getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setSupportZoom(false);
        webSettings.setDisplayZoomControls(false);

        webSettings.setAllowFileAccess(true);
        webSettings.setLoadWithOverviewMode(true);

        // 自适应屏幕
        //webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        // 支持插件
        //webSettings.setPluginState(WebSettings.PluginState.ON);
        // webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // 支持内容重新布局
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        //webSettings.supportMultipleWindows();
        //webSettings.setSupportMultipleWindows(true);
        loadUrl("file:///android_asset/chart_quxian.html");
    }

    WebViewLoadfinishListener listener;

    public void setListener(WebViewLoadfinishListener listener) {
        this.listener = listener;
    }

    private void initWebViewClient() {
        setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                if (listener != null) {
                    listener.onWebViewLoadfinishListener();
                }
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request,
                                        WebResourceError error) {
                super.onReceivedError(view, request, error);
            }
        });
    }



    public void initData(String value, String time) {
        String optionValue = value.toString();
        String optionTime = time.toString();
        String call = "javascript:initData('" + optionValue + "','" + optionTime + "')";
        // String call = "javascript:initData('" + optionValue + "')";
        Log.i("chart", "测试数据" + call);
        loadUrl(call);
    }

    /**
     * 显示Echart自带的默认样式的Loading
     */
    public void myChartShowLoading() {
        String call = "javascript:myChartShowLoading()";
        //loadUrl(call);
        shouldCallJsFunctionArray.add(call);
    }

    /**
     * 隐藏Echart自带的默认样式的Loading
     */
    public void myChartHideLoading() {
        String call = "javascript:myChartHideLoading()";
        loadUrl(call);
    }


    ///////////////////////WebAppEChartInterface////////////////////////////////

    /**
     * js 与 Android原生交互接口
     */
    class WebAppEChartInterface {
        Context context;

        public WebAppEChartInterface(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void showDebugMessage(String message) {
            if (isDebug) Log.i("chart", message);
        }

        /**
         * 获取图表配置JSON数据
         *
         * @return
         */
        @JavascriptInterface
        public String getChartOptions() {

            return null;
        }


        /**
         * 添加图表事件响应监听
         *
         * @param params echart返回的事件信息 http://echarts.baidu.com/api.html#events
         */
        @JavascriptInterface
        public void addEchartActionHandlerResponseResult(String params) {
            Log.i("chart", params);
            if (onAddEchartActionHandlerResponseResultListener != null) {
                onAddEchartActionHandlerResponseResultListener.actionHandlerResponseResult(params);
            }
        }


        /**
         * 移除图表事件响应监听
         *
         * @param params echart返回的事件信息 http://echarts.baidu.com/api.html#events
         */
        @JavascriptInterface
        public void removeEchartActionHandlerResponseResult(String params) {
            Log.i("chart", params);
        }

    }

    ///////////////////////WebAppEChartInterface////////////////////////////////

    ////////////////////////////数据源 获取图表的JSON配置//////////////////////////////

    private DataSource dataSource;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        reload();
    }

    public DataSource getDataSource() {

        return dataSource;
    }

    public interface DataSource {

    }
    ////////////////////////////数据源 获取图表的JSON配置//////////////////////////////


    ////////////////////////////添加事件监听echart返回的 事件相关属性（是一个json），将该json返回给开发者使用
    ///////////////////////////echart返回的事件信息:http://echarts.baidu.com/api.html#events

    private OnAddEchartActionHandlerResponseResultListener onAddEchartActionHandlerResponseResultListener;

    public void setOnAddEchartActionHandlerResponseResultListener(OnAddEchartActionHandlerResponseResultListener onAddEchartActionHandlerResponseResultListener) {
        this.onAddEchartActionHandlerResponseResultListener =
                onAddEchartActionHandlerResponseResultListener;
    }

    public OnAddEchartActionHandlerResponseResultListener getOnAddEchartActionHandlerResponseResultListener() {

        return onAddEchartActionHandlerResponseResultListener;
    }

    public interface OnAddEchartActionHandlerResponseResultListener {
        void actionHandlerResponseResult(String result);
    }

}
